var express = require('express');
var router = express.Router();
var { usersModel } = require("../untils/model.js")
var { aesEncrypt } = require('../untils/index')
var moment = require("moment")

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

router.post('/register', function (req, res, next) {
  var body = req.body
  console.log(body);
  // res.json({
  //   msg: "注册成功",

  // })

  usersModel.findOne({
    $or: [
      { username: body.username },
      { phone: body.phone }
    ]
  })
    .then(data => {
      console.log(data);
      if (data) {
        res.send(`<script>alert('注册失败，用户已存在');location.href= '/register'</script>`)

      } else {
        body.time = new Date()
        usersModel.insertMany(body)
          .then(result => {
            res.send(`<script>alert('注册成功,请登录！');location.href = '/login?username=${aesEncrypt(body.username)}'</script>`)
          })
          .catch(err => {
            res.send(`<script>alert('注册失败');location.href= '/register'</script>`)

          })
      }
    })
})


router.post('/signon', (req, res) => {
  var body = req.body;
  console.log(moment().format("YYYY-MM-DD HH:mm:ss"));
  usersModel.findOne({
    $or: [
      { username: body.username },
      { phone: body.phone }
    ]
  }).then(result => {
    if (result.password == body.password) {
      req.session.username = result.username
      req.session.phone = result.phone
      req.session.loginTime = moment().format("YYYY-MM-DD HH:mm:ss")
      res.redirect('/')  //重定向
    } else {
      res.send(`<script>alert('登录失败，用户名或密码错误');location.href='/login'</script>`)
    }
  }).catch(err => {
    console.log(err);
    res.send(`<script>alert('登录失败，未知错误');location.href='/login'</script>`)

  })
})


// //注销
// router.get('/logout',(req,res)=>{
//   req.session.destroy(()=>{
//     res.redirect("/") 
//   })
// })
module.exports = router;
